import { ref } from 'vue';

interface RequestOptions<T = any> {
  onSuccess?: (_res: T) => void;
  onError?: (_err: any) => void;
  onFinally?: () => void;
}

export function useRequest() {
  const loading = ref(false);

  async function run<T>(fn: () => Promise<T>, options: RequestOptions<T> = {}) {
    if (loading.value) return;
    loading.value = true;
    try {
      const res = await fn();
      options.onSuccess?.(res);
      return res;
    } catch (err) {
      options.onError?.(err);
      throw err;
    } finally {
      loading.value = false;
      options.onFinally?.();
    }
  }

  return { loading, run };
}
